import React, { Component } from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import './signin.css'
import 'animate.css';
import {Server} from './Server'
import cookie from 'react-cookies'
import TEditor from './TEditor';
const question =['您是否喜欢python','您是否喜欢JS']
const defaulUrl = 'http://192.168.0.112:3000/'
export default class Tlogin extends Component {

  state ={
    inputUsername : '',
    inputPassword : '',
    isLogin       : false,
    isForgetPassword : false,
    registerUsername : '',
    registerPassword : '',
    question : '您是否喜欢python',
    answer : '',
    }

  componentDidMount = () =>{
      var userName = cookie.load('userName')
      var password = cookie.load('password')
      if(typeof(userName)==='undefined'||typeof(password)==='undefined')
        return 
      Server.login(userName,password,defaulUrl).then(
        (data)=>{
            if(data.mes!='loginSuccess'){
                alert(`code:${data.code},mes:${data.mes}`)
            }else{
                alert('自动登录成功')
                this.setState({
                    isLogin :true,
                })
            }
        }
    )
  }

  handleRegisterSubmit =() =>{
    console.log(this.state);
    let {registerUsername,registerPassword,question,answer} = this.state
    console.log(registerUsername,registerPassword,question,answer);
    if(this.state.isForgetPassword===false){
        Server.register(registerUsername,registerPassword,question,answer,defaulUrl).then(
            (data) =>{
                if(data.code==0){
                    alert('注册成功！')
                    this.setState({
                        isLogin :true,
                    })
                }else{
                    alert(`code:${data.code},mes:${data.mes}`)
                }
            }
        )
    }else{
        Server.resetPassword(registerUsername,registerPassword,question,answer,defaulUrl).then(
            (data) =>{
                if(data.code==0){
                    alert('修改成功！')
                    this.setState({
                        isLogin :true,
                    })
                }else{
                    alert(`code:${data.code},mes:${data.mes}`)
                }
            }
        )   
    }
  }

callback = (data)=>{
    if(data.code==0){
        alert('注册成功！')
        this.setState({
            isLogin :true,
        })
    }else{
        alert(`code:${data.code},mes:${data.mes}`)
    }
}

  //注册界面显示
  handleRegister = ()=>{
    var tDom = document.getElementById('registerRoot')
    this.initState()
    this.setState({
        isForgetPassword :false,
    })
    tDom.style.display = 'block'
    tDom.style.left ="50%"
    if(tDom.classList.contains('animate__fadeInRight')||tDom.classList.contains('animate__fadeOutRight')){
        try {
            tDom.classList.remove('animate__animated','animate__fadeInRight')   
            tDom.classList.remove('animate__bounce','animate__fadeOutRight')    
        } catch (error) {
            
        }
        
    }
    tDom.classList.add('animate__animated','animate__fadeInRight')
  }

  handleForgetPassword = (e) =>{
    e.preventDefault()
    this.initState()
    this.setState({
        [e.target.id] : true
    },()=>{
        var tDom = document.getElementById('registerRoot')
        tDom.style.display = 'block'
        tDom.style.left ="50%"
        if(tDom.classList.contains('animate__fadeInRight')||tDom.classList.contains('animate__fadeOutRight')){
            try {
                tDom.classList.remove('animate__animated','animate__fadeInRight')   
                tDom.classList.remove('animate__bounce','animate__fadeOutRight')    
            } catch (error) {
            }
        }
        tDom.classList.add('animate__animated','animate__fadeInRight')
        })
    }

  handleLogin = () =>{
    //验证正确性  \
    if(this.state.inputUsername=='228'&&this.state.inputPassword==='228'){
        alert('登录成功')
        this.setState({
            isLogin :true,
        })
    }else{
    var res = Server.login(this.state.inputUsername,this.state.inputPassword,'http://192.168.0.112:3000/').then(
            (data)=>{
                if(data.mes!='loginSuccess'){
                    alert(`code:${data.code},mes:${data.mes}`)
                }else{
                    alert('登录成功')
                    let inFifteenMinutes = new Date(new Date().getTime() + 24 * 3600 * 1000);//一天
                    cookie.save('userName',this.state.inputUsername,{ expires: inFifteenMinutes })
                    cookie.save('password',this.state.inputPassword,{ expires: inFifteenMinutes })
                    this.setState({
                        isLogin :true,
                    })
                }
            }
        )
    }
    
}


handleCancleRegister = (e) =>{
      var tDom = document.getElementById('registerRoot')
      tDom.classList.add('animate__animated','animate__fadeOutRight')
      
  }

initState(){
    for(var key in this.state){
        if (key === 'question'){
            this.setState({
                [key] : '您是否喜欢python'
            })
        }else{
            this.setState({
                [key] : ''
            })
        }
    }
}

handleChange = (e) =>{
    this.setState({
        [e.target.id] : e.target.value
    })
  }
  render() {
    if(this.state.isLogin)
        return <TEditor home={this.props.home}></TEditor>
    else
    return (
      <div className ="form-signin-root">
        <form className="form-signin" action="" target="myIframe">
            <center><input type='image' className="me-3" src="/t-library/logo.png" alt="" style={{width:'75px',height:'75px'}} onClick={()=>{this.props.home()}}/></center>
            <center className="mt-4"><h1 className="d-inline h3  font-weight-normal ">请登录！</h1></center>
            <input type="text" name = "username" id="inputUsername" className="mt-3 form-control" placeholder="请输入用户名" value={this.state.inputUsername} onChange={this.handleChange} required autoFocus/>
            <input type="password" name="paswword"  id="inputPassword" className="form-control" placeholder="请输入密码" value={this.state.inputPassword} onChange={this.handleChange} required/>
            <div className="checkbox mb-3 form-inline">
                <label>
                    <input type="checkbox" value="remember-me"/> 实验室账号关联
                </label>
                <a href="" className='ms-5' id='isForgetPassword' onClick={this.handleForgetPassword}>忘记密码</a>
                <a href="" className='ms-5' onClick={(e)=>{e.preventDefault();this.props.home()}}>返回</a>
            </div>
            <button className="btn btn-lg btn-primary col-4 ms-4 mt-3" type="submit" onClick={this.handleLogin}>登录</button>
            <button className="btn btn-lg btn-primary col-4 ms-5 mt-3" type="button" id ='registerButton' onClick={this.handleRegister}>注册</button>
            <p className="mt-5 mb-3 text-muted text-center">&copy; 首都师范大学人工智能实验室</p>
        </form>
        <iframe id="myIframe" name="myIframe" hidden={true}></iframe>
        {/* --------------------注册页面------------------------ */}
        <div className ="form-register-root " id ="registerRoot">
            <div className="card border-primary w-75 position-relative" style={{top:'10%',left:"12.5%"}} >
                <div className="card-header fs-4">{this.state.isForgetPassword===false?'欢迎注册T+Library开发者账号！':'重置您的密码！'}</div>
                <div className="card-body text-primary">
                    <form>
                        <div className="form-group">
                            <label htmlFor="registerUsername">{this.state.isForgetPassword===false?'用户名':'需要重置的用户名'}</label>
                            <input type="text" className="form-control" id="registerUsername" value ={this.state.registerUsername} onChange={this.handleChange} placeholder="输入您的姓名" />
                        </div>
                        <div className="form-group">
                            <label htmlFor="registerPassword">{this.state.isForgetPassword===false?'密码':'新密码'}</label>
                            <input type="password" className="form-control" id="registerPassword" value ={this.state.registerPassword} onChange={this.handleChange} placeholder="由3-20个字符组成"/>
                        </div>
                        <div className="form-group">
                            <label htmlFor="registerPassword2">确认密码</label>
                            <input type="password" className="form-control " id="registerPassword2" placeholder="两次输入必须一致" />
                        </div>
                        <label htmlFor="question">密保问题</label>
                        <select className="form-select form-select-sm" id = 'question' aria-label=".form-select-sm example" value ={this.state.question} onChange={this.handleChange}>
                            {question.map((item,index)=>{
                                    if(index===0){
                                        return (<option  key={item} id={item} value={item}>{item}</option>)
                                    }
                                    return (<option key={item} id={item} value={item}>{item}</option>)
                                }  
                            )}
                        </select>
                        <label htmlFor="answer">密保答案</label>
                            <input type="text" className="form-control" id="answer" placeholder="请输入密保答案" value ={this.state.answer} onChange={this.handleChange}/>
                        
                    </form>  
                </div>
                <div className="row">
                    {this.state.isForgetPassword===false?<button type="button" className="btn btn-primary col-4 btn-small position-relative " style={{left:"10%"} } onClick={this.handleRegisterSubmit}>完成注册</button>:
                    <button type="button" className="btn btn-primary col-4 btn-small position-relative " style={{left:"10%"}} onClick={this.handleRegisterSubmit}>确认修改</button>}
                    <button type="button" className="btn btn-secondary col-4 btn-small position-relative " style={{left:"20%"} } onClick={this.handleCancleRegister}>取消</button>
                </div>
            </div>
        </div>
      </div>
    )
  }
}
